<template>
  <a-layout class="layout">
    <a-layout-header  class="searchHeader" style="background-color: white; box-shadow: -10px 10px 10px -10px rgba(0, 0, 0, 0.3); height: 60px" >
      <SearchHeader  :title='pageTitle'/>
    </a-layout-header>

    <!-- 导航栏-->
    <div :bordered="false" :style="{backgroundColor: '#f2f2f2',height: '100%'}">
      <div :bordered="false" :style="{backgroundColor: '#f2f2f2',height: '100%'}">
        <main class="km-page">
          <div  class="km-top-line">
            <div class="ant-breadcrumb">
              <a>
                <span @click="jumpManage('defaultDocSearch')">
              <i class="el-icon-arrow-left ant-breadcrumb"></i>
              <span class="ant-breadcrumb">返回</span></span></a>
            </div>
          </div>

          <div class="km-context-right">
            <!--标题内容-->
            <div style="background: white;border-radius: 10px;margin-bottom: 20px;">
              <a-form :pagination="ipagination" layout="inline"  style="min-height: 10px">
                <a-row style="background: white">
                  <a-col style="background-color: #081C42">
                    <h3 style="color: #ffffff;margin-left: 10px;padding:5px">
                      <i class="el-icon-tickets" style="font-size: 17px; min-width: 20px; color: #00baff;"></i>
                      <b>标题：{{dataSource.title}}</b>
                    </h3>
                  </a-col>
                  <div class="model-info">
                   <span style="margin-right: 15px;margin-left: 30px;">
                     <i class="el-icon-user"></i>作者：
                     <span style="color: rgb(0, 12, 23);">{{dataSource.createBy}}</span>
                   </span>
                    <span style="margin-right: 15px;">
                     <i class="el-icon-alarm-clock"></i>发布时间：
                      <span style="color: rgb(0, 12, 23);">{{dataSource.createTime}}</span>
                   </span>
                    <span style="margin-right: 15px;" v-if="dataSource.publicRemark==1">
                     <i class="el-icon-unlock"></i>公开方式：
                     <span style="color: rgb(0, 12, 23);">主动公开</span>
                   </span>
                    <span style="margin-right: 15px;" v-if="dataSource.publicRemark==2">
                     <i class="el-icon-lock"></i>公开方式：
                     <span style="color: rgb(0, 12, 23);">不公开</span>
                   </span>
                  </div>

                  <div class="km-content-model" style="border-radius: 5px; background: white; margin-bottom: 15px;">
                    <span class="items-s-line" style="margin-right: 17px;margin-left: 35px;" v-if="dataSource.category!=null">
                     <i class="el-icon-date"></i>知识分类：
                     <span class="line-s-item" v-if="this.category!=''">{{this.category.text}}</span>
                   </span>

                    <template>
                      <quill-editor
                        v-show="shouldShowEditor"
                        style="margin-left: 15px;"
                        :readonly="true"
                        v-model="dataSource.remark"
                        ref="myQuillEditor"
                        :options="editorOptions"
                        class="custom-quill-editor"
                        @focus="onEditorFocus($event)"
                      ></quill-editor>
                    </template>
                    <el-empty :image-size="100" v-if="dataSource.remark==null" description="无内容"></el-empty>

                    <div class="model-info">
                   <span style="margin-right: 15px;margin-left: 15px;">
                     <i class="el-icon-notebook-2"></i>来源：
                     <span style="color: rgb(0, 12, 23);" v-if="this.source!=''&&source!=undefined">{{source.text}}</span>
                   </span>

                      <template>
                        <div class="preview-container">
                          <div class="ant-space ant-space-horizontal ant-space-align-center">
      <span :title="'预览数：'+dataSource.views" class="preview-count-wrapper">
        <a-icon
          type="eye"
          :title="'预览数：'+dataSource.views"
          :style="{ fontSize: '15px', color: '#0078ff'}"
        />
        <span class="preview-count" :title="'预览数：' + dataSource.views">{{ dataSource.views }}</span>
      </span>
                          </div>
                        </div>
                      </template>

                    </div>

                  </div>
                </a-row>
              </a-form>
            </div>

            <!--附件-->
            <div style="background: white;border-radius: 10px;margin-bottom: 20px;" v-if="dataSource.fileId !== null || dataSource.fileId!==undefined|| dataSource.fileId!==''">
              <a-form :pagination="ipagination" layout="inline"  style="min-height: 10px">
                <a-row style="background: white">
                  <a-col style="background-color: #ffffff">
                    <h3 style="color: #000000;margin-left: 10px;padding:5px">
                      <i class="el-icon-paperclip" style="font-size: 17px; min-width: 20px; color: #00baff;"></i>
                      <b>附件</b>
                    </h3>
                  </a-col>
                  <div class="km-file-lists">
                    <div class="km-file-items">
                      <div class="km-file-items-t">
                        <img v-if="dataSource.fileType ==='pdf'||dataSource.fileType ==='pptx'" src="~@/assets/pdfs.png" class="file-icon"/>
                        <img v-else-if="dataSource.fileType ==='doc'||dataSource.fileType ==='docx'||dataSource.fileType ==='xlsx'" src="~@/assets/word.png" class="file-icon"/>
                        <img v-else-if="dataSource.fileType ==='jpg'||dataSource.fileType ==='jpeg'||dataSource.fileType ==='png'||dataSource.fileType ==='gif'||dataSource.fileType ==='bmp'||dataSource.fileType ==='svg'" src="~@/assets/tupian.png" class="file-icon"/>
                        <img v-else src="~@/assets/pdfs.png" class="file-icon"/>
                        <p class="title">{{dataSource.name}}</p>
                        <span  style="color: rgb(92, 96, 101); font-size: 13px;">
                    大小：{{dataSource.fileSize}}KB
                  </span>
                      </div>
                      <div class="km-file-items-d op-item">
                       <span title="下载" class="highlight" @click="downloadKmDoc(dataSource)">
                       <a-icon v-if="dataSource.downloadFlag==1" type="download" title="下载"
                               :style="{ fontSize: '16px', color: '#5c6065'}"/>
                       <a-divider type="vertical"/>下载</span>
                        <span :title="'预览'" class="highlight"  @click="previewKmDoc(dataSource)">
                       <a-icon style="cursor: pointer;" type="eye"  :title="'预览'"
                               :style="{ fontSize: '15px', color: '#5c6065', }"></a-icon><a-divider type="vertical"/>预览</span>
                      </div>
                    </div>
                  </div>
                </a-row>
              </a-form>

              <b-j-modal :title="title"
                         :width="width"
                         :visible="visible"
                         @cancel="handleCancel"
                         cancelText="关闭"
                         :okButtonProps="{ class:{'jee-hidden': true} }">
                <div>
                  <div>
                    <p-d-f-modal iframe-i-d="pdfIDde" :p-d-furl="PDFurl" :iframeWidth="width"/>
                  </div>
                </div>
              </b-j-modal>
            </div>

          </div>

        </main>
      </div>
     </div>

  </a-layout>
</template>

<script>
  import {getDictItemsFromCache} from '@/api/api'
  import SearchHeader from '../Common/SearchHeader';
  import {getAction,httpAction,httpPostAction,  downloadFileName} from '@/api/manage'
  import SubjectModal from '../filemanagement/modules/SubjectModal'
  import Vue from "vue";
  import VueQuillEditor from 'vue-quill-editor';
  import 'quill/dist/quill.core.css'; // 引入样式
  import 'quill/dist/quill.snow.css'; // 引入样式
  Vue.use(VueQuillEditor)

    export default {
        name: "Knowledge",
      props: {
        title: {
          type: String,
          default: ''
        },
        list: {
          type: Array,
          default: null
        },
        height: {
          type: Number,
          default: null
        }
      },
      components: {SearchHeader,SubjectModal, 'vue-quill-editor': VueQuillEditor.quillEditor},
      data() {
        return {
          editor: null,
          docId: '',
          title: "预览",
          width: '900',
          dataSource: [],
          //  过滤字段数据
          filterOptions: [],
          filterCategorys: [],
          filterDictCode: 'km_dict_source',
          filterCategory: 'km_dict_category',
          source: '',
          category: '',
          editorOptions: {
            modules: {
              toolbar: false, // 将 toolbar 设置为 false 隐藏工具栏
            },
          },
          visible: false,
          pdfLoading: false,
          pdfShow: true,
          PDFurl: '',
          url: {
            list: '/KM/kmDoc/queryById',
            downloadKmDoc: "/KM/kmDoc/downloadKmDoc",
            addFavouriteKmDoc: '/KM/kmDocFavourite/add',
            delFavouriteKmDoc: '/KM/kmDocFavourite/delete',
            previewKmDoc: '/KM/kmDoc/previewKmDoc',
          },
         }
        },

      computed: {
        // 计算属性来判断是否应该显示编辑器
        shouldShowEditor() {
          return this.dataSource.remark !== null && this.dataSource.remark !== '';
        }
      },

      created() {
        console.log("------testId------" + JSON.stringify(this.$route.query.id))
        this.docId = this.$route.query.id
        let params = {id:this.docId};
        getAction(this.url.list,params).then((res)=>{
          if(res.success){
            this.dataSource = res.result
            console.log("------知识返回值------" + JSON.stringify(this.dataSource))
            if (this.dataSource.source!=null||this.dataSource.source!="") {
              this.initFilterDict();
            }
          if (this.dataSource.category!=null||this.dataSource.category!="") {
              this.initCategory();
            }
          }
        })
     },
      mounted() {
        this.$nextTick(() => {
          const quill = this.$refs.myQuillEditor.quill;
          quill.enable(false); // 禁用编辑器
        });
        this.editor = this.$refs.myQuillEditor.quill;
        this.addImageClickEvent();
      },
      methods: {
        //下载文件
        downloadKmDoc(record) {
          this.$notification.success({
            message: '文件开始下载...',
            duration: 1,
          });
          downloadFileName(this.url.downloadKmDoc, {docId: record.id})
        },

        //加收藏夹
        addFavouriteKmDoc(record) {
          let httpurl = '';
          let method = '';
          httpurl += this.url.addFavouriteKmDoc;
          method = 'post';
          console.info("-------id-------" + JSON.stringify(record.id))
          httpPostAction(httpurl, {docId: record.id}, method).then((res) => {
            if (res.success) {
              this.$message.success("收藏成功!");
              record.favourite = 1;
            } else {
              this.$message.warning("收藏失败!");
            }
          }).finally(() => {
          })
        },

        //取消收藏夹
        delFavouriteKmDoc(record) {
          let httpurl = '';
          let method = '';
          httpurl += this.url.delFavouriteKmDoc;
          method = 'delete';
          httpPostAction(httpurl, {docId: record.id}, method).then((res) => {
            if (res.success) {
              this.$message.success("取消收藏成功!");
              record.favourite = 0;
            } else {
              this.$message.warning("取消收藏失败!");
            }
          }).finally(() => {
          })
        },

        // 显示预览窗口，初始化
        previewKmDoc(record) {
          console.info("-------预览-------" + JSON.stringify(record.id))
            this.PDFurl =  this.url.previewKmDoc + "?docId=" + record.id;
            this.title ='预览 - ' + record.title;
            this.visible = true;
            this.pdfLoading = true;
            this.pdfShow = true;
        },
        //关闭预览窗口
        handleCancel() {
          this.visible = false;
        },

        onEditorFocus(event) {
          event.enable(false);
        }, // 获得焦点事件

        // 读取字典来源
        initFilterDict() {
          console.log("------来源------")
          this.filterOptions = [];
          let options = getDictItemsFromCache(this.filterDictCode)
          if(options){
            options.forEach((item, index) => {
              let filterOption = {};
              filterOption.text = item.title;
              filterOption.value = item.value;
              this.filterOptions.push(filterOption);
            });
            this.source = this.filterOptions.find(option => {
                return option.value === this.dataSource.source;
            });
          }
        },

        // 读取知识分类
        initCategory() {
          console.log("------分类------")
          this.filterOptions = [];
          let options = getDictItemsFromCache(this.filterCategory)
          if(options){
            options.forEach((item, index) => {
              let filterOption = {};
              filterOption.text = item.title;
              filterOption.value = item.value;
              this.filterCategorys.push(filterOption);
            });
            this.category = this.filterCategorys.find(option => {
              return option.value === this.dataSource.category;
            });
          }
        },

        jumpManage(defaultDocSearch) {
          // 使用 Vue Router 的 resolve 方法来获取完整的 URL
          const route = this.$router.resolve({ name: defaultDocSearch });
          // 更新 window.location 来触发页面的重新加载
          window.location.href = route.href;
        },


        addImageClickEvent() {
          const editor = this.editor;
          editor.container.addEventListener('click', (event) => {
            const target = event.target;
            if (target.tagName === 'IMG') {
              event.preventDefault();
              this.zoomImage(target);
            }
          }, true);
        },
        zoomImage(imgElement) {
          const zoomContainer = document.createElement('div');
          zoomContainer.style.position = 'fixed';
          zoomContainer.style.top = '0';
          zoomContainer.style.left = '0';
          zoomContainer.style.right = '0';
          zoomContainer.style.bottom = '0';
          zoomContainer.style.display = 'flex';
          zoomContainer.style.justifyContent = 'center';
          zoomContainer.style.alignItems = 'center';
          zoomContainer.style.background = 'rgba(0, 0, 0, 0.8)';
          zoomContainer.style.zIndex = '9999';
          document.body.appendChild(zoomContainer);

          const enlargedImage = new Image();
          enlargedImage.src = imgElement.src;
          enlargedImage.style.maxWidth = '90%';
          enlargedImage.style.maxHeight = '90%';
          enlargedImage.style.position = 'absolute';
          enlargedImage.style.border = '3px solid white';
          enlargedImage.style.boxShadow = '0 4px 8px rgba(0,0,0,0.5)';
          enlargedImage.style.cursor = 'zoom-out';
          enlargedImage.style.transition = 'transform 0.25s ease';

          let scale = 1; // Initial scale

          enlargedImage.onmousedown = (e) => {
            e.preventDefault();
            const mouseX = e.clientX;
            const mouseY = e.clientY;
            const imgX = e.offsetX;
            const imgY = e.offsetY;

            const mouseMoveHandler = (e) => {
              const dx = e.clientX - mouseX;
              const dy = e.clientY - mouseY;
              const distance = Math.sqrt(dx * dx + dy * dy);

              scale = distance / Math.hypot(imgX, imgY) * 2 + 0.5; // Zoom factor

              enlargedImage.style.transform = `scale(${scale})`;
            };

            const mouseUpHandler = () => {
              document.removeEventListener('mousemove', mouseMoveHandler);
              document.removeEventListener('mouseup', mouseUpHandler);
            };

            document.addEventListener('mousemove', mouseMoveHandler);
            document.addEventListener('mouseup', mouseUpHandler);
          };

          enlargedImage.onclick = () => {
            zoomContainer.remove();
          };

          document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
              zoomContainer.remove();
            }
          });

          zoomContainer.appendChild(enlargedImage);
        },

        //  显示专题
        showModel(model) {
          console.log("=====model.topicIds_dictText======" + JSON.stringify(model.topicIds_dictText))
          this.$refs.modalForm.edit(model, 0);
          this.$refs.modalForm.title = "选择专题"
          // // 确保更新是响应式的
          this.$nextTick(() => {
            this.$set(model, 'topicIds_dictText', model.topicIds_dictText);
          });
        },


      }


    }

</script>

<style scoped>
  @media (min-width: 1200px) {
    .km-page {
      width: 70%;
      margin: auto;
    }
  }
  .km-top-line{
    margin: 25px 0 10px 0;
  }

  .ant-breadcrumb {
    font-size: 14px; /* 根据您的设计调整字体大小 */
    color: rgb(0, 0, 0); /* 默认面包屑颜色 */
  }

  @media (min-width: 1200px) {
    .km-context-right {
      width: 100%;
      float: right;
    }
  }

  .km-file-lists {
    padding: 10px;
  }

  .km-file-items{
    display: inline-block;
    border-radius: 5px;
    margin-bottom: 10px;
    padding: 10px;
  }

  @media (min-width: 2000px) {
    .km-file-items {
      width: 42%;
    }
  }

  .km-file-items-t{
    border-radius: 5px;
    margin-bottom: 1px;
    padding: 5px;
  }

  .file-icon{
    width: 33px;
    height: 43px;
    float: left;
    margin-right: 10px;
  }

  .km-file-items-t .title{
    color: #000;
    margin-bottom: 2px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .line-s-item, .op-item {
    font-size: 12px;
    padding: 3px 8px;
    height: 28px;
    line-height: 28px;
    margin-right: 5px;
    color: #5c6065;
  }

  .km-file-items-d {
    height: 30px;
    line-height: 30px;
    text-align: left;
    -webkit-font-feature-settings: "tnum";
    font-feature-settings: "tnum";
  }

  .km-file-items-d span {
    padding: 0 15px;
    color: #000c17;
    cursor: pointer;
  }

  .highlight {
     color: #00008b;
     font-weight: 400;
     cursor: pointer;
  }

  .model-info span{
    color: #666;
  }

  .items-s-line {
    color: #9e9e9e;
    font-size: 11px;
  }

  .items-s-lines {
    font-size: 16px;
  }

  @media (min-width: 2000px) {
    .km-content-model{
      min-height: 100px;
    }
  }


  .custom-quill-editor /deep/.ql-container {
    border: none; /* 移除边框 */
    box-shadow: none; /* 移除阴影 */
  }

  .preview-container {
    float: right;
    margin-right: 20px; /* 根据需要调整这个值 */
  }

  .preview-count-wrapper {
    display: flex;
    align-items: center;
  }

  .preview-count {
    margin-left: 8px; /* 与图标的间距 */
  }

  .line-s-item {
    font-size: 10px;
    padding: 3px 8px;
    height: 28px;
     line-height: 28px;
     margin-right: 5px;
     color: #999b9d;
    background: #dedede;
    border-radius: 8px;
  }
</style>